var News = require('../models/news.model');
var Cate = require('../models/cate.model');
exports.create = function (req, res, next) {
    const news = new News(req.body);
    news.save().then(data => {
        res.json(data);
    });
}

exports.update = function (req, res, next) {
    var id = req.params.id;
    News.findByIdAndUpdate(id, {
        $set: req.body
    }, {
        new: false
    }).then(data => {
        res.json(data);
    });
}
exports.get2 = function (req, res, next) {
    var id = req.params.id;
    News.findById(id).then(data => {
        res.json(data);
    });
}
exports.get = function (req, res, next) {
    // var id = req.body.id;
    var page = req.body.page ? req.body.page : 1;
    var rows = req.body.rows ? req.body.rows : 5;
    var cate = {};
    if (req.body.title && req.body.title.length > 0) {
        cate = {
            title: req.body.title
        }

    }
    News.paginate(cate, {
        page: +page,
        limit: +rows
    }, function (err, result) {
        result.rows = result.docs;
        delete result.docs;
        res.json(result);
    });
}
exports.delete = function (req, res, next) {
    var id = req.params.id;
    News.findByIdAndDelete(id).then(data => {
        res.json(data);
    });
}
exports.removes = function (req, res, next) {
    var ids = req.body.ids.split(',');
    News.remove({
        _id: {
            $in: ids
        }
    }).then(function () {
        res.json({
            'message': 'success',
            status: 200
        });
    });
}
exports.list = function (req, res, next) {
    var page = req.body.page ? req.body.page : 1;
    var rows = req.body.rows ? req.body.rows : 5; 
    var ids = req.body.ids;
    if (ids) {
        News.paginate({
            cateId: {
                $in: ids
            }
        }, {
            page: +page,
            limit: +rows
        }, function (err, result) {
            result.rows = result.docs;
            delete result.docs;
            res.json(result);
        });
    } else {
        News.paginate({}, {
            page: +page,
            limit: +rows
        }, function (err, result) {
            result.rows = result.docs;
            delete result.docs;
            res.json(result);
        });
    }



}


